package model

import (
	"database/sql"
	"encoding/json"
	"time"
	"errors"
)

type (
	WhiteItem struct {
		Id          		int    	`json:"id"`
		Phone       		string 	`json:"phone"`
		Status      		int    	`json:"status"`
		CreatedDate 		int    	`json:"created_date"`
		UpdatedDate 		int    	`json:"updated_date"`
	}
)

func redisWhiteList() (ret []*WhiteItem, err error) {
	err = rdb.Del(ctx, "white_list").Err()
	if err != nil {
		return ret, err
	}

	rows, err := db.Query("SELECT * FROM white_list ORDER BY updated_date DESC, status DESC")
	if err != nil {
		return ret, err
	}

	defer rows.Close()

	for rows.Next() {
		w := WhiteItem{}
		err := rows.Scan(&w.Id, &w.Phone, &w.Status, &w.CreatedDate, &w.UpdatedDate)
		if err != nil {
			return ret, err
		}
		ret = append(ret, &w)

		jsonStu, err := json.Marshal(w)
		if err != nil {
			return ret, err
		}
		err = rdb.RPush(ctx, "white_list", jsonStu).Err()
		if err != nil {
			return ret, err
		}
	}

	return ret, nil
}

func (w *WhiteItem) QueryWhiteList(status string, phone string) (ret []*WhiteItem, err error) {
	sql1 := "SELECT * FROM white_list WHERE"
	if len(status) > 0 && len(phone) == 0 {
		sql1 += " status = " + status
	} else if len(status) == 0 && len(phone) > 0 {
		sql1 += " phone = " + phone
	} else {
		sql1 += " status = " + status + " AND phone = " + phone
	}

	sql1 += " ORDER BY updated_date DESC"

	rows, err := db.Query(sql1)
	if err != nil {
		return ret, err
	}

	for rows.Next() {
		w := WhiteItem{}
		err := rows.Scan(&w.Id, &w.Phone, &w.Status, &w.CreatedDate, &w.UpdatedDate)
		if err != nil {
			return ret, err
		}
		ret = append(ret, &w)
	}

	defer rows.Close()

	return ret, nil
}

func (w *WhiteItem) GetWhiteList() (ret []*WhiteItem, err error) {
	vals, err := rdb.LRange(ctx, "white_list", 0, -1).Result()
	if err != nil {
		return nil, err
	}

	if len(vals) > 0 {
		for _, v := range vals {
			w := WhiteItem{}
			err := json.Unmarshal([]byte(v), &w)
			if err != nil {
				return ret, err
			}

			ret = append(ret, &w)
		}

		return ret, nil
	}

	ret, err = redisWhiteList()
	if err != nil {
		return ret, err
	}

	return ret, nil
}

func (w *WhiteItem) CreateWhite(phone string) error {
	stmt, err := db.Prepare("SELECT id FROM promotion_officer WHERE phone=?")
	if err != nil {
		return err
	}

	var pid int
	err = stmt.QueryRow(phone).Scan(&pid)
	if err != nil && err != sql.ErrNoRows {
		return err
	}

	if err == sql.ErrNoRows {
		return errors.New("未查询到此电话号码对应的推广官")
	}

	stmt1, err := db.Prepare("SELECT id FROM white_list WHERE phone=?")
	if err != nil {
		return err
	}

	var wid int
	err = stmt1.QueryRow(phone).Scan(&wid)
	if err != nil && err != sql.ErrNoRows {
		return err
	}

	if err == sql.ErrNoRows {
		stmt1, err := db.Prepare("INSERT white_list SET phone=?, status=?, created_date=?, updated_date=?")
		if err != nil {
			return err
		}

		_, err = stmt1.Exec(phone, 0, time.Now().Unix(), time.Now().Unix())
		if err != nil {
			return err
		}

		_, err = redisWhiteList()
		if err != nil {
			return err
		}
		return nil
	} else {
		return errors.New("白名单中已存在此电话号码")
	}
}

func (s *WhiteItem) UpdateWhite(id int, status int) error {
	stmt, err := db.Prepare("UPDATE white_list SET status=?, updated_date=? WHERE id=?")
	if err != nil {
		return err
	}

	_, err = stmt.Exec(status, time.Now().Unix(), id)
	if err != nil {
		return err
	}

	_, err = redisWhiteList()
	if err != nil {
		return err
	}

	return nil
}